package admin

import (
    //"net/http"
    "time"
    "html/template"

    "github.com/gin-gonic/gin"

    "mygin/app/models"
    . "mygin/app/helpers"
)

// 首页路由处理器方法
func Index(c *gin.Context) {
    Initialize(c)


    // 总订单
    totalOrder := 0
    // 总订单金额
    orderAmount := 0
    // 总商品
    totalGoods := 0
    // 本月会员
    monthUser := 0
    // 总会员
    totalUser := 0
    // 订单统计
    orderStatistics := getOrderStatistics()

    dada := map[string]interface{} {
        "totalOrder" : totalOrder,
        "orderAmount" : orderAmount,
        "totalGoods" : totalGoods,
        "monthUser" : monthUser,
        "totalUser" : totalUser,
        "orderStatistics" : orderStatistics,
    }

    dadas := map[string]interface{} {
        "adminInfo" : adminInfo,
        "sidebar" : template.HTML(sidebar),
        "data" : dada,
    }

    GenerateHTML(c.Writer, "admin/layouts/app", dadas, "admin/layouts/app", "admin/partials/header", "admin/partials/sidebar", "admin/dashboard/index")
}

// 订单统计
func getOrderStatistics() (map[string]interface{}) {
    now := time.Now()

    startTime := now.Unix() - 3600 * 24 * 10 // 10天前
    length := 20
    days := []string{}
    countOrders := []int{}
    totalAmounts := []float32{}

    timeLayout := "2006-01-02"
    for i := 0; i <= length; i++ {
        dayTime := startTime + int64(i * 86400)
        //datetime := time.Unix(dayTime, 0).Format(timeLayout)
        startDay := dayTime
        endDay := startDay + int64(i * 86400)

        countOrderSql := "SELECT count(*) FROM articles WHERE created_at > ? AND created_at < ?"
        countOrder := models.CountDatas(countOrderSql, startDay, endDay)
        amountOrderSql := "SELECT sum(id) FROM articles WHERE created_at > ? AND created_at < ?"
        totalAmount := models.SumDatasAmount(amountOrderSql, startDay, endDay)

        days = append(days, time.Unix(dayTime, 0).Format(timeLayout))
        countOrders = append(countOrders, countOrder)
        totalAmounts = append(totalAmounts, totalAmount / 100)
    }

    statistics := map[string]interface{} {
        "day" : days,
        "countOrder": countOrders,
        "totalAmount": totalAmounts,
    }
    //jsonStatistics, _ := json.Marshal(statistics)
    //return string(jsonStatistics)

    return statistics
}
